#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ == taoyulong2018@gmail.com
# __time__ == 2023/9/11 18:24
# ===========================================
#       题目名称： 54. 螺旋矩阵
#       题目地址： https://leetcode.cn/problems/spiral-matrix/
#       题目描述： https://note.youdao.com/s/VjIUrvCD
# ===========================================
from typing import List


class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        while matrix:
            # # 从左向右
            while matrix and len(matrix[0]) > 0:
                res.append(matrix[0].pop(0))
            if matrix and not matrix[0]:
                del matrix[0]

            # 从右向下
            if matrix:
                for i in range(len(matrix)):
                    if matrix[i]:
                        res.append(matrix[i].pop())


            # 从下向左
            while matrix and len(matrix[-1]) > 0:
                res.append(matrix[-1].pop())
            if matrix and not matrix[-1]:
                del matrix[-1]

            # # 从左向上
            if matrix:
                for i in reversed(range(len(matrix))):
                    if matrix[i]:
                        res.append(matrix[i].pop(0))

        return res


if __name__ == '__main__':
    s = Solution()
    # [1,2,3,6,9,8,7,4,5]
    print(s.spiralOrder(matrix=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
    # [1,2,3,4,8,12,11,10,9,5,6,7]
    print(s.spiralOrder(matrix=[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))
